import axios from "axios";
import { ElMessage } from "element-plus";
import Qs from "qs";
import store from "@/store";
import router from "@/router";

// import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000, // 请求超时时间,
});

// request请求拦截器
service.interceptors.request.use(
  (config) => {
    console.log(config);
    if (config.method === "post") {
      config.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
      config.data = Qs.stringify(config.data);
    }
    config.headers["Authorization"] = store.state.user.access_token;
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone响应拦截器
service.interceptors.response.use(
  (response) => response,
  (error) => {
    console.log("err" + error); // for debug
    if (error.response) {
      const { status } = error.response;
      if (status === 400) {
        ElMessage.error(`请求参数错误`);
      } else if (status === 401) {
        router.push({
          path: "/login",
          query: { redirect: router.currentRoute.value.fullPath },
        });
      } else if (status === 403) {
        ElMessage.error(`没有权限`);
      } else if (status === 404) {
        ElMessage.error(`请求资源不存在`);
      } else {
        ElMessage.error(`服务端错误`);
      }
    } else if (error.resquest) {
      ElMessage.error(`请求超时,请刷新重试!`);
    } else {
      ElMessage.error(`请求失败:${error.message}`);
    }

    return Promise.reject(error);
  }
);
export default service;
